package cn.phecda.boot.tenant.core.spring;

import cn.phecda.boot.common.lang.model.TenantContext;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;

/**
 * <p> 租户任务装饰器。当执行异步任务时，租户信息必须带入到异步线程中 </p>
 *
 * @author : wanpinwei
 */
public class TenantAwareTaskDecorator implements TaskDecorator {

    @Override
    @NonNull
    public Runnable decorate(@NonNull Runnable runnable) {
        String tenantId = TenantContext.get();
        return () -> {
            try {
                TenantContext.set(tenantId);
                runnable.run();
            } finally {
                TenantContext.clear();
            }
        };
    }
}
